import { LinkOutlined } from "@ant-design/icons";
import {
  IconToBottom,
  IconDelete,
  IconEdit,
} from "@arco-design/web-react/icon";
import {
  Popover,
  Table,
  Button,
  Message,
  Progress,
} from "@arco-design/web-react";
import { memo, useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { useAppDispatch, useAppSelector } from "../../../../store";
import { PatientCheckTaskWrapper } from "./style";
import {
  fetchGetTaskExaminationAction,
  fetchPatientRateAction,
  fetchUpdateTaskExaminationAction,
} from "../../../../store/modules/patient";

import dayjs from "dayjs";
import {
  exportExaminations,
  exportTasks,
} from "../../../../service/modules/patient";

interface TaskItem {
  id: number;
  state: string | null;
  timeOn: string | null;
  deadline: string | null;
}
interface ExaminationItem {
  id: number;
  state: string | null;
  timeOn: string | null;
}
const TaskModificationById = () => {
  const [selectedRowKeys, setSelectedRowKeys] = useState<any[]>([]);
  const dispatch = useAppDispatch();
  const { id } = useParams<{ id: string }>();
  const [deleteParams, setDeleteParams] = useState<
    {
      id: number;
      timeOn: string | null;
      deadline: string | null;
      state: string | null;
      type: string;
    }[]
  >([]);
  const { modificationAndTaskList, getRate } = useAppSelector(
    (state) => state.patient
  );
  useEffect(() => {
    dispatch(fetchPatientRateAction(Number(id)));
    dispatch(fetchGetTaskExaminationAction({ userId: Number(id) }));
  }, [dispatch]);
  //?将检查和任务数据合并
  const combinedData = [
    ...(modificationAndTaskList?.tasksVO || []).map((item: any) => ({
      ...item,
      type: "task",
    })),
    ...(modificationAndTaskList?.examinationsVO || []).map((item: any) => ({
      ...item,
      type: "examination",
    })),
  ];
  const combinedTypeData = [
    ...combinedData.map((item: any) => ({
      ...item,
      key: `${item.type}-${item.id}`,
    })),
  ];

  /**
   * @表单
   */

  // console.log(combinedData);

  /**
   * @删除
   */
  const updateTaskExamination = async (record: any) => {
    console.log(record);
    Message.error("由于没有对应的接口，不好删除删除请在病人管理页面进行删除，");
  };

  /**
   * @导出
   */
  //! 在组件内部添加导出函数
  const handleExport = async () => {
    try {
      // 导出任务
      if (modificationAndTaskList?.tasksVO?.length) {
        const taskRes = await exportTasks({
          userId: Number(id),
          // 可以添加其他查询参数
        });
        downloadFile(taskRes, `任务列表_${dayjs().format("YYYYMMDD")}.xlsx`);
      }

      // 导出检查
      if (modificationAndTaskList?.examinationsVO?.length) {
        const examRes = await exportExaminations({
          userId: Number(id),
          // 可以添加其他查询参数
        });
        downloadFile(examRes, `检查列表_${dayjs().format("YYYYMMDD")}.xlsx`);
      }
      Message.success("导出成功");
    } catch (error) {
      Message.error("导出失败");
      console.error("导出失败:", error);
    }
  };

  // 下载文件工具函数
  const downloadFile = (blobData: Blob, fileName: string) => {
    const blob = new Blob([blobData]);
    const downloadElement = document.createElement("a");
    const href = window.URL.createObjectURL(blob);
    downloadElement.href = href;
    downloadElement.download = fileName;
    document.body.appendChild(downloadElement);
    downloadElement.click();
    document.body.removeChild(downloadElement);
    window.URL.revokeObjectURL(href);
  };

  //   console.log(combinedData);
  const columns = [
    {
      title: "标题",
      dataIndex: "title",
      key: "title",
      render: (value: string, record: any) =>
        record.type === "task" ? record.title : record.name,
    },
    {
      key: "timeOn",
      title: "开始时间",
      dataIndex: "timeOn",
      render: (value: string) =>
        dayjs(value).format("YYYY年MM月DD日") || "未设置",
    },
    {
      title: "截止时间",
      dataIndex: "deadline",
      key: "deadline",

      render: (value: string, record: any) =>
        record.type === "task"
          ? dayjs(value).format("YYYY年MM月DD日") || "未设置"
          : "",
    },
    {
      title: "评分标准",
      dataIndex: "ratingCriteria",
      key: "ratingCriteria",
      render: (value: string, record: any) => {
        // console.log(record);
        return (
          <Popover
            trigger="hover"
            content={
              <span>
                {record.type === "task"
                  ? record.ratingCriteria
                  : "暂无评分标准"}
              </span>
            }
          >
            <span className="ratingCriteria">
              {record.type === "task" ? record.ratingCriteria : "暂无评分标准"}
            </span>
          </Popover>
        );
      },
    },
    {
      title: "操作",
      dataIndex: "movement",
      key: "movement",
      render: (_: any, record: any) => (
        <Button
          status="danger"
          icon={<IconDelete />}
          onClick={() => updateTaskExamination(record)}
        >
          删除
        </Button>
      ),
    },
  ];
  /**
   * @单选框列表
   */
  const onSelectChange = (newSelectedRowKeys: any) => {
    console.log("selectedRowKeys changed: ", newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection = {
    selectedRowKeys,

    onChange: onSelectChange,
  };
  return (
    <PatientCheckTaskWrapper>
      <div className="headerWrapper">
        <div className="item">
          <Button status="danger" icon={<IconDelete />}>
            删除
          </Button>
        </div>
        <div className="item">
          <Button
            status="warning"
            icon={<IconToBottom />}
            onClick={handleExport}
          >
            导出
          </Button>
        </div>
        <div className="item">
          <Button status="success" disabled icon={<IconEdit />}>
            任务完成情况
          </Button>
        </div>

        <Progress
          width={300}
          size="large"
          animation
          percent={getRate.rate * 100}
        ></Progress>

        {/* <Progress size="large" percent={40}></Progress> */}
      </div>
      <div className="tableWrapper">
        <Table
          rowKey={(record) => `${record.type}-${record.id}`}
          rowSelection={rowSelection}
          data={combinedTypeData}
          columns={columns}
          pagination={false}
        ></Table>
      </div>
    </PatientCheckTaskWrapper>
  );
};
export default memo(TaskModificationById);
